package tcp

import (
	log "github.com/sirupsen/logrus"
	"net"
	"runtime/debug"
)

type TcpClient struct {
	Handle func(conn ConnChannelInterface)
	Conn   *ConnChannel
}

// Close 关闭连接
func (c *TcpClient) Close() {
	err := c.Conn.Close()
	if err != nil {
		log.Warning("TcpClient Close error!! -->", err)
	}
}

// Dial 链接server
func (c *TcpClient) Dial(network, addr string) (err error) {
	defer func() {
		if over := recover(); over != nil {
			if e, ok := over.(error); ok {
				err = e
			} else {
				log.Error(over)
				debug.PrintStack()
			}
		}
	}()

	var netConn net.Conn
	if netConn, err = net.Dial(network, addr); err != nil {
		return err
	}

	c.Conn = NewConnChannel(netConn)

	// 开始处理
	c.Handle(c.Conn)
	// 断开链接
	defer c.Close()

	return err
}
